package com.photovoltaic.auth.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.photovoltaic.auth.entity.Permission;
import com.photovoltaic.auth.entity.Role;
import com.photovoltaic.auth.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper extends BaseMapper<User> {
    
    /**
     * 获取用户通过角色获得的权限
     */
    @Select("SELECT p.* FROM permission p " +
            "JOIN role_permission rp ON p.id = rp.permission_id " +
            "JOIN user_role ur ON rp.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId}")
    List<Permission> getUserRolePermissions(@Param("userId") Integer userId);
    
    /**
     * 获取用户的直接权限
     */
    @Select("SELECT p.* FROM permission p " +
            "JOIN user_permission up ON p.id = up.permission_id " +
            "WHERE up.user_id = #{userId}")
    List<Permission> getUserDirectPermissions(@Param("userId") Integer userId);
    
    /**
     * 获取用户的所有权限（包括直接权限和通过角色获得的权限）
     */
    @Select("SELECT DISTINCT p.* FROM permission p " +
            "WHERE p.id IN (" +
            "  SELECT rp.permission_id FROM role_permission rp " +
            "  JOIN user_role ur ON rp.role_id = ur.role_id " +
            "  WHERE ur.user_id = #{userId} " +
            "  UNION " +
            "  SELECT up.permission_id FROM user_permission up " +
            "  WHERE up.user_id = #{userId}" +
            ")")
    List<Permission> getUserPermissions(@Param("userId") Integer userId);
    
    /**
     * 获取用户的所有角色
     */
    @Select("SELECT r.* FROM role r " +
            "JOIN user_role ur ON r.id = ur.role_id " +
            "WHERE ur.user_id = #{userId}")
    List<Role> getUserRoles(@Param("userId") Integer userId);
} 